import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

import '../../base/imageres.dart';
import '../../base/constant.dart';
import '../../base/eventbus.dart';
import '../../base/log.dart';
import '../../base/stringres.dart';
import '../../base/theme.dart';
import '../../database/app_data.dart';
import '../../native/nativechannel.dart';
import '../../util/toast_util.dart';
import '../../views/jsw_base_view.dart';

///女性健康下面的生理周期规律性
class PeriodicLawPage extends StatefulWidget {
  final bool isReset;
  final int regularly;
  final int menstrualTime;
  final int cycleValue;
  final int periodValue;

  const PeriodicLawPage(
      {super.key,
        required this.isReset,
        required this.regularly,
        required this.menstrualTime,
        required this.cycleValue,
        required this.periodValue});

  @override
  State<StatefulWidget> createState() {
    return _PeriodicLawPageState();
  }
}

class _PeriodicLawPageState extends State<PeriodicLawPage> {
  static const _tag = '[page_periodic_law.dart][_PeriodicLawPageState]';

  StreamSubscription? _bus;

  ///用户ID
  var _userId = "";

  ///生理周期规律的值(1：规律 0：不规律)
  int _regularly = -1;

  ///最近一次月经的时间戳
  int _menstrualTime = 0;

  ///生理周期的值
  var _cycleValue = 0;

  ///月经期天数
  var _periodValue = 0;

  @override
  void initState() {
    super.initState();
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
        overlays: SystemUiOverlay.values);
    if (widget.isReset) {
      _regularly = widget.regularly;
    }
    _initEventBus();
    Native.readUserId();
    _menstrualTime = widget.menstrualTime;
    _cycleValue = widget.cycleValue;
    _periodValue = widget.periodValue;
  }

  @override
  void dispose() {
    _cancelEventBus();
    super.dispose();
  }

  ///初始化EventBus
  void _initEventBus() {
    _bus = EventBusUtil.getInstance().on().listen((event) {
      switch (event.runtimeType) {
        case NativeEvent:
          NativeEvent nativeEvent = event;
          switch (nativeEvent.type) {
            case HealthNativeDataType.READ_USER_ID:
              _userId = nativeEvent.data["token"];
              break;
          }
          break;
      }
    });
  }

  ///取消EventBus订阅
  void _cancelEventBus() {
    _bus?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage(ImageRes.bg_health_set),
              fit: BoxFit.cover, // 图片填充方式
            ),
          ),
        ),
        JSWBaseView(
          bodyColor: Colors.transparent,
          head: AppBar(
            elevation: 0.0,
            backgroundColor: Colors.transparent,
            title: EasyTouch(
              width: double.infinity,
              padding: const EdgeInsets.only(right: 55),
              child: Text(
                widget.isReset ? StringRes.periodic_law_content : StringRes.women_cycle_title,
                textAlign: TextAlign.center,
                style: ThemeUtil.toolbar,
              ),
            ),
            leading: IconButton(
              splashColor: Colors.transparent,
              highlightColor: Colors.transparent,
              hoverColor: Colors.transparent,
              icon: const Icon(
                Icons.arrow_back,
                color: Colors.white,
              ),
              onPressed: () {
                Get.back();
              },
            ),
          ),
          body: Column(
            children: [
              //内容
              Container(
                  margin: const EdgeInsets.only(top: 30, left: 20, right: 20),
                  child: Text(
                    textAlign: TextAlign.center,
                    StringRes.women_law_content,
                    style: ThemeUtil.h1.copyWith(fontSize: 20)
                  )),

              //提示
              Container(
                  margin: const EdgeInsets.only(top: 10, left: 20, right: 20),
                  child: Text(
                    StringRes.women_law_tips,
                    textAlign: TextAlign.center,
                    style: ThemeUtil.p2.copyWith(
                        color: const Color(ThemeUtil.primaryWhiteValue50)),
                  )),

              //规律布局
              EasyTouch(
                width: double.infinity,
                onPressed: () async {
                  //点击规律
                  DartLog.i(_tag, '点击规律...');
                  setState(() {
                    _regularly = 1;
                  });
                },
                child: Container(
                    width: double.infinity,
                    margin: const EdgeInsets.only(top: 30, left: 15, right: 15),
                    padding: const EdgeInsets.only(
                        top: 10, bottom: 10, left: 21, right: 21),
                    decoration: BoxDecoration(
                      color: Colors.white12,
                      borderRadius: BorderRadius.circular(20.0), // 设置圆角半径
                      border: Border.all(
                          width: 1,
                          color: _regularly == 1
                              ? Colors.white70
                              : Colors.transparent),
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          textAlign: TextAlign.left,
                          StringRes.rule,
                          style: ThemeUtil.p2.copyWith(fontFamily: 'Medium'),
                        ),
                        Container(
                            margin: const EdgeInsets.only(top: 2),
                            child: Text(
                              StringRes.rule_tips,
                              style: ThemeUtil.p2.copyWith(
                                  fontSize: 13,
                                  color: const Color(
                                      ThemeUtil.primaryWhiteValue50)),
                            )),
                      ],
                    )),
              ),

              //不规律布局
              EasyTouch(
                width: double.infinity,
                onPressed: () async {
                  //点击规律
                  DartLog.i(_tag, '点击不规律...');
                  setState(() {
                    _regularly = 0;
                  });
                },
                child: Container(
                    width: double.infinity,
                    margin: const EdgeInsets.only(top: 10, left: 15, right: 15),
                    padding: const EdgeInsets.only(
                        top: 10, bottom: 10, left: 21, right: 21),
                    decoration: BoxDecoration(
                      color: Colors.white12,
                      borderRadius: BorderRadius.circular(20.0), // 设置圆角半径
                      border: Border.all(
                          width: 1,
                          color: _regularly == 0
                              ? Colors.white70
                              : Colors.transparent),
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          textAlign: TextAlign.left,
                          StringRes.irregular,
                          style: ThemeUtil.p2.copyWith(fontFamily: 'Medium'),
                        ),
                        Container(
                            margin: const EdgeInsets.only(top: 2),
                            child: Text(
                              StringRes.irregular_tips,
                              style: ThemeUtil.p2.copyWith(
                                  fontSize: 13,
                                  color: const Color(
                                      ThemeUtil.primaryWhiteValue50)),
                            )),
                      ],
                    )),
              ),
            ],
          ),
          bottom: Container(
            margin: EdgeInsets.only(
                bottom: 30 + MediaQuery.of(context).viewPadding.bottom,
                left: 30,
                right: 30),
            child: //下一步按钮
            Container(
              height: 50,
              alignment: Alignment.center,
              decoration: ThemeUtil.themeConStyle,
              child: TextButton(
                style: ThemeUtil.themebtnStyle,
                onPressed: () {
                  if (_regularly == -1) {
                    ToastUtil.show(StringRes.select_women_law_tips);
                    return;
                  }
                  DartLog.i(_tag, "保存本地的周期规律性：$_regularly");

                  if (widget.isReset) {
                    EventBusUtil.getInstance().fire(DataEvent(
                        HealthDataType.REFRESH_SETTING_REGULARLY, _regularly));
                    Get.back();
                  } else {
                    //同步女性健康服务器成功
                    var timeString = DateFormat("yyyy-MM-dd").format(
                        DateTime.fromMillisecondsSinceEpoch(_menstrualTime));
                    // 显示等待框
                    showLoadingDialog();
                    APPDatabase.saveWomanHealthData(
                        _userId,
                        timeString,
                        timeString,
                        _periodValue,
                        _cycleValue,
                        _regularly,
                        1)
                        .then((value) {
                      if (value) {
                        DartLog.i(
                            _tag, "保存本地的月经最近的一次时间：$_menstrualTime $timeString");
                        Map<String, dynamic> dataMap = <String, dynamic>{};
                        dataMap['health_menstrual_time'] = timeString;
                        dataMap['health_cycle_value'] = _cycleValue;
                        dataMap['health_period_length'] = _periodValue;
                        dataMap['health_regularly'] = _regularly;
                        dataMap['health_tracking'] = 1;
                        if (Native.HealthDataApp == 1) {
                          Get.offAllNamed(PageIndex.mainHealthPage);
                        } else if (Native.HealthDataApp == 2) {
                          Get.until((route) =>
                          route.settings.name == "/mainbarController");
                          Future.delayed(const Duration(milliseconds: 50), () {
                            Get.toNamed(PageIndex.mainFlutterHealthPage);
                          });
                        }
                        Native.setWomenHealthData(dataMap);
                      }
                      hideLoadingDialog();
                    });
                  }
                },
                child: Text(
                    widget.isReset ? StringRes.confirm : StringRes.finish,
                    textAlign: TextAlign.center,
                    style: ThemeUtil.p2),
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 显示加载等待框
  BuildContext? _dialogContext;

  void showLoadingDialog() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          _dialogContext = context;
          return const Center(
            child: CircularProgressIndicator(
              color: Color(ThemeUtil.primarProgressValue),
            ),
          );
        },
      );
    });
  }

  /// 隐藏加载等待框
  void hideLoadingDialog() {
    if (_dialogContext != null && Navigator.canPop(_dialogContext!)) {
      Navigator.pop(_dialogContext!);
      _dialogContext = null;
    }
  }
}
